<template>
  <div class="app-container">
    <el-card>
      <!-- 筛选条件区域 -->
      <div class="filter-container">
        <el-form :model="listQuery" label-width="auto">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="6">
              <el-form-item label="分类名">
                <el-input v-model.trim="listQuery.name" @input.native="filterPercentChar" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="6">
              <el-form-item label="类型">
                <el-input v-model.trim="listQuery.type" @input.native="filterPercentChar" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="6">
              <el-form-item label-width="0">
                <el-button type="primary" @click="handleFilter">查询</el-button>
                <el-button @click="resetList">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 按钮区域 -->
      <div class="btn-container">
        <el-button type="primary" icon="el-icon-plus" @click="handleCreate"> 添加 </el-button>
      </div>

      <!-- 表格区域 -->
      <el-table :data="list" border highlight-current-row :stripe="true">
        <el-table-column label="#" width="60">
          <template slot-scope="{ $index }">
            <span>{{ $index + (listQuery.page - 1) * listQuery.limit + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分类名" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="类型" prop="type" :show-overflow-tooltip="true" />
        <el-table-column label="代码" prop="code" width="60" :show-overflow-tooltip="true" />
        <el-table-column label="排序" prop="sort" width="60" :show-overflow-tooltip="true" />
        <el-table-column label="更新时间" prop="updTime" width="170" :show-overflow-tooltip="true" />
        <el-table-column label="描述" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column label="操作" width="150">
          <template slot-scope="{ row, $index }">
            <el-button type="primary" size="mini" @click="handleUpdate(row)"> 编辑 </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row, $index)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </el-card>

    <!-- 添加/编辑 对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" @close="resetForm('dataForm')">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px">
        <el-form-item label="分类名" prop="name">
          <el-input v-model.trim="temp.name" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="temp.type" clearable filterable allow-create default-first-option placeholder="请选择或输入类型（类型由大写字母、数字、下划线组成，以大写字母开头）">
            <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="代码" prop="code">
          <el-input v-model.trim="temp.code" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="temp.sort" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model.trim="temp.remark" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData('dataForm') : updateData('dataForm')"> 确 定 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTags, getOneTag, addTags, updateTags, deleteTags } from '@/api/content/tags' // 分类管理接口
import Pagination from '@/components/Pagination' // 分页组件
import { validEncode1 } from '@/utils/validate' // 表单验证

export default {
  name: 'ContentTags',
  components: { Pagination },
  data() {
    return {
      list: [], // 列表数据
      total: 0, // 总数
      listQuery: {
        // 查询列表参数
        page: 1,
        limit: 10,
        name: undefined,
        type: undefined
      },
      temp: {
        // 表单数据
        name: undefined,
        type: undefined,
        code: undefined,
        sort: 0,
        remark: undefined
      },
      dialogFormVisible: false, // 控制添加、编辑对话框显示或隐藏
      dialogStatus: '', // 添加、编辑对话框的状态 'create'或'update'
      textMap: {
        // 添加、编辑对话框的标题
        update: '编辑',
        create: '添加'
      },
      rules: {
        // 表单验证规则
        name: [
          { required: true, message: '请输入分类名', trigger: 'blur' },
          { min: 1, max: 10, message: '长度不能大于10位', trigger: 'blur' }
        ],
        type: [{ required: true, validator: validEncode1, trigger: 'change' }],
        code: [{ required: true, message: '请输入代码', trigger: 'blur' }],
        sort: [{ required: true, type: 'number', message: '请输入数字', trigger: 'blur' }],
        remark: [{ max: 200, message: '长度不能大于200位', trigger: 'blur' }]
      },
      typeList: [
        // 预置的类型，防止页面上使用的类型被删除完后不记得类型了
        {
          value: 'STANDARD_NAME',
          label: 'STANDARD_NAME'
        },
        {
          value: 'YES_NO',
          label: 'YES_NO'
        },
        {
          value: 'TYPE',
          label: 'TYPE'
        },
        {
          value: 'CHANNEL_TYPE',
          label: 'CHANNEL_TYPE'
        },
        {
          value: 'TAG_ID',
          label: 'TAG_ID'
        }
      ]
    }
  },
  created() {
    // 组件创建完成
    this.getList()
  },
  methods: {
    async getList() {
      // 获取分类列表
      try {
        const {
          data: { records, total }
        } = await getTags(this.listQuery)
        this.list = records
        this.total = total
      } catch (error) {
        console.log(error)
      }
    },
    handleFilter() {
      // 查询
      this.listQuery.page = 1
      this.getList()
    },
    resetList() {
      // 重置
      this.listQuery = {
        page: 1,
        limit: 10,
        name: undefined,
        type: undefined
      }
      this.getList()
    },
    handleCreate() {
      // 点击添加按钮
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    createData(formName) {
      // 添加
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            const { message } = await addTags(this.temp)
            this.dialogFormVisible = false
            this.$message({
              message: message,
              type: 'success'
            })
            this.getList()
          } catch (error) {
            console.log(error)
          }
        }
      })
    },
    async handleUpdate(row) {
      // 点击编辑按钮
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      const { data } = await getOneTag(row.id)
      this.temp = data
    },
    updateData(formName) {
      // 更新
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            const { message } = await updateTags(this.temp)
            this.dialogFormVisible = false
            this.$message({
              message: message,
              type: 'success'
            })
            this.getList()
          } catch (error) {
            console.log(error)
          }
        }
      })
    },
    handleDelete(row, index) {
      // 点击删除按钮
      this.$confirm('此操作将删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { message } = await deleteTags(row.id)
          this.$message({
            type: 'success',
            message: message
          })
          this.getList()
        })
        .catch(() => {})
    },
    resetForm(formName) {
      // 对话框关闭时重置表单
      this.temp = {
        name: undefined,
        type: undefined,
        code: undefined,
        sort: 0,
        remark: undefined
      }
      this.$refs[formName].resetFields()
    }
  }
}
</script>
